package com.kou.backend.handler;

import com.kou.backend.resposne.ResultResponse;
import com.kou.backend.util.JsonUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 401未登录 or token失效返回结果
 *
 * @author: Kou
 * @since: 2023/8/31 20:47
 */
@Component
public class BackendAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.setStatus(401);
        response.getWriter().write(JsonUtils.toJSONString(ResultResponse.fail("401", authException.getMessage())));
        response.getWriter().flush();
    }
}
